package com.lagou.rpc.consumer.configuration;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import java.util.List;

public class RpcScannerConfigurer implements BeanDefinitionRegistryPostProcessor, InitializingBean, ApplicationContextAware, BeanNameAware {

    private ApplicationContext applicationContext;

    private List<String> beanNameList;

    private RpcFactoryBean rpcFactoryBean = new RpcFactoryBean();

    private BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        for (String beanName : beanNameList) {
            RootBeanDefinition rootBeanDefinition = new RootBeanDefinition();
            rootBeanDefinition.setBeanClassName(beanName);
            rootBeanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
            rootBeanDefinition.setBeanClass(this.rpcFactoryBean.getClass());
            rootBeanDefinition.getPropertyValues().add("interfaceName", beanName);
            rootBeanDefinition.setLazyInit(false);
            rootBeanDefinition.setPrimary(true);
            rootBeanDefinition.setAutowireCandidate(true);
            String shortClassName = beanNameGenerator.generateBeanName(rootBeanDefinition,beanDefinitionRegistry);
            beanDefinitionRegistry.registerBeanDefinition(shortClassName, rootBeanDefinition);
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

    }

    @Override
    public void setBeanName(String s) {

    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void setBeanNameList(List<String> beanNameList) {
        this.beanNameList = beanNameList;
    }
}
